<template>
  <div class="container">
    <div class="sidebar">
      <div style="display: flex; align-items: center;">
        <el-input placeholder="请输入关键字搜索" v-model="searchKey" style="margin-right: 8px;"></el-input>
        <el-button type="info" @click="search" style="background-color: orange;">
          搜索
        </el-button>
      </div>
      <div class="tree-container">
        <el-tree :data="treeData" :empty-text="emptyText" node-key="dict_type_id" :props="defaultProps"
          default-expand-all @node-click="handleNodeClick" class="letree"></el-tree>
      </div>
    </div>
    <div class="main">
      <div class="header">
        <el-button type="primary" @click="openDialog(null)">新建</el-button>
        <el-button type="success" @click="importData">导入</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <el-select v-model="selectedFilter" @change="handleFilterChange">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" />
        <el-button type="info" @click="query" style="background-color: orange;">
          查询
        </el-button>
        <el-button type="info" @click="reset">重置</el-button>
      </div>
      <el-table :empty-text="emptyText" :data="tableData" border class="eltable"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="dictionary_id" v-if="false"></el-table-column>
        <el-table-column prop="dictionary_code" label="字典项编码"></el-table-column>
        <el-table-column prop="dictionary_name" label="字典项名称"></el-table-column>
        <el-table-column v-if="false" prop="dictionary_type" label="字典项类型"></el-table-column>
        <el-table-column prop="dictionary_notes" label="字典项说明" width="425"></el-table-column>
        <el-table-column label="启用" width="70">
          <template #default="{ row }">
            <el-switch v-model="row.dictionary_state" :active-value="1" :inactive-value="0"
              @change="updateState(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="text" @click="openDialog(row)">
              编辑
            </el-button>
            <el-button type="text" @click="deleteRow(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="total, prev, pager, next, jumper"></el-pagination>
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
      <el-form :model="newDictForm" :rules="rules" ref="newDictFormRef" label-width="120px">
        <el-form-item label="字典项编码" prop="Code">
          <el-input v-model="newDictForm.Code" :readonly="true" />
        </el-form-item>
        <el-form-item label="字典项名称" prop="Name">
          <el-input v-model="newDictForm.Name" placeholder="请输入字典项名称" />
        </el-form-item>
        <el-form-item label="字典项类型" prop="Type">
          <el-select v-model="newDictForm.Type" placeholder="请选择字典项类型">
            <el-option v-for="type in dictTypes" :key="type.dict_type_id" :label="type.dict_type_name"
              :value="type.dict_type_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="字典项说明" prop="Notes">
          <el-input v-model="newDictForm.Notes" placeholder="请输入字典项说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="confirmAdd">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  setup() {
    const emptyText = '暂无数据';
    const searchKey = ref('');
    const searchTable = ref('');
    const treeData = ref([]);
    const selectedNodeId = ref(null);
    const defaultProps = {
      children: 'children',
      label: 'dict_type_name',
      value: 'dict_type_id'
    };
    const tableData = ref([]);
    const selectedFilter = ref('1'); // 默认为启用
    const currentPage = ref(1);
    const pageSize = ref(15);
    const totalItems = ref(0);
    const multipleSelection = ref([]);
    const isAllSelected = ref(false);

    // 新增弹窗
    const dialogVisible = ref(false);
    const dialogTitle = ref('');
    const newDictForm = ref({
      Id: null,
      Code: '',
      Name: '',
      Type: null,
      Notes: ''
    });
    const newDictFormRef = ref(null);
    const dictTypes = ref([]);
    const editingRow = ref(null);

    // 表单验证规则
    const rules = {
      Name: [{ required: true, message: '请输入字典项名称', trigger: 'blur' }],
      Type: [{ required: true, message: '请选择字典项类型', trigger: 'change' }]
    };

    // 获取树形数据
    const treeTableData = () => {
      axios.get('/api/Dict/GetTypes')
        .then(res => {
          treeData.value = res.data;
          if (treeData.value.length > 0) {
            selectedNodeId.value = 0;
            fetchTableData(selectedNodeId.value);
          }
        })
        .catch(err => {
          console.error('Error loading tree data:', err);
          ElMessage.error('加载树数据失败，请稍后再试');
        });
    };

    // 获取表格数据
    const fetchTableData = (nodeId) => {
      const params = {
        type: nodeId || selectedNodeId.value || 0,
        state: selectedFilter.value,
        page: currentPage.value,
        pageSize: pageSize.value
      };
      axios.get('/api/Dict/GetDict', { params })
        .then(res => {
          console.log(res.data)
          tableData.value = res.data.dictionaries; // 获取当前页数据
          totalItems.value = res.data.zon; // 获取总条目数
        })
        .catch(err => {
          console.error('Error fetching data:', err);
          ElMessage.error('加载数据失败，请稍后再试');
        });
    };

    // 搜索功能
    const search = () => {
      if (!searchKey.value) {
        treeTableData();
        return;
      }
      axios.get(`/api/Dict/GetType?str=${searchKey.value}`)
        .then((response) => {
          treeData.value = response.data;
          ElMessage.success("搜索成功");
        })
        .catch((error) => {
          console.error("搜索失败", error);
          ElMessage.error("搜索失败，请稍后再试");
        });
    };

    const handleFilterChange = () => {
      console.log('Selected Filter:', selectedFilter.value);
      console.log('Selected Node ID:', selectedNodeId.value);
      if (!searchKey) {
        fetchTableData(selectedNodeId.value); // 使用当前的 selectedNodeId
      } else {
        searchTableData(selectedNodeId.value);
      }
    };

    // 表格搜索框输入数据模糊查询
    const query = () => {
      searchTableData(selectedNodeId.value);
    };

    const searchTableData = (nodeId) => {
      if (!searchTable.value) {
        fetchTableData(nodeId);
        return;
      }
      const params = {
        type: nodeId || selectedNodeId.value || 0,
        state: selectedFilter.value,
        str: searchTable.value,
        page: currentPage.value,    // 添加分页参数
        pageSize: pageSize.value    // 添加分页参数
      };
      axios.get('/api/Dict/GetDict', { params })
        .then(res => {
          tableData.value = res.data.dictionaries; // 获取当前页数据
          totalItems.value = res.data.zon; // 获取总条目数
        })
        .catch(err => {
          console.error('Error fetching data:', err);
          ElMessage.error('加载数据失败，请稍后再试');
        });
    };

    // 更新状态
    const updateState = (row) => {
      ElMessageBox.confirm('改变状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/api/Dict/StateChange?id=${row.dictionary_id}&state=${row.dictionary_state}`)
          .then(response => {
            if (response.data === true) {
              ElMessage.success('状态已更新');
            } else {
              ElMessage.error('更新失败，后端返回错误');
            }
            if (!searchKey) {
              fetchTableData(selectedNodeId.value);
            } else {
              searchTableData(selectedNodeId.value); // 刷新表格
            }
          })
          .catch(err => {
            console.error('Error:', err);
            ElMessage.error('更新失败');
          });
      }).catch(() => {
        if (!searchKey) {
          fetchTableData(selectedNodeId.value);
        } else {
          searchTableData(selectedNodeId.value); // 刷新表格
        }
        ElMessage.info('已取消改变');
      });
    };

    // 获取字典项类型
    const fetchDictTypes = async () => {
      try {
        const response = await axios.get('/api/Dict/GetTypes');
        dictTypes.value = response.data;
      } catch (error) {
        console.error('获取字典项类型失败:', error);
        ElMessage.error('获取字典项类型失败，请稍后再试');
      }
    };

    // 打开弹窗
    const openDialog = async (row) => {
      await fetchDictTypes();
      dialogVisible.value = true;
      if (row) {
        dialogTitle.value = '编辑字典项';
        editingRow.value = row;
        newDictForm.value = {
          Id: row.dictionary_id,
          Code: row.dictionary_code,
          Name: row.dictionary_name,
          Type: row.dictionary_type,
          Notes: row.dictionary_notes
        };
      } else {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
        const day = String(now.getDate()).padStart(2, '0'); // 补零

        // 生成四位随机数
        const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

        // 拼接时间字符串和随机数
        const formattedTime = `${year}${month}${day}`;
        let code = `ZD${formattedTime}${randomNumber}`;

        dialogTitle.value = '新增字典项';
        editingRow.value = null;
        newDictForm.value = {
          Id: null,
          Code: code,
          Name: '',
          Type: selectedNodeId.value || null,
          Notes: ''
        };
      }
    };

    // 关闭弹窗
    const closeDialog = () => {
      dialogVisible.value = false;
      newDictForm.value = {
        Id: null,
        Code: '',
        Name: '',
        Type: null,
        Notes: ''
      };
      editingRow.value = null;
    };

    const confirmAdd = async () => {
      try {
        // 确保表单验证通过
        await newDictFormRef.value.validate();

        const formAddData = {
          dictionary_code: newDictForm.value.Code,
          dictionary_name: newDictForm.value.Name,
          dictionary_type: newDictForm.value.Type,
          dictionary_notes: newDictForm.value.Notes || ''
        };

        const formUpdateData = {
          dictionary_id: editingRow.value ? editingRow.value.dictionary_id : null,
          dictionary_code: newDictForm.value.Code,
          dictionary_name: newDictForm.value.Name,
          dictionary_type: newDictForm.value.Type,
          dictionary_notes: newDictForm.value.Notes || ''
        };

        console.log("Request Data:", formAddData);

        let response;
        if (editingRow.value) {
          // 更新操作
          response = await axios.put(
            '/api/Dict/UpdateDict',
            formUpdateData
          );
        } else {
          // 新增操作
          response = await axios.post(
            '/api/Dict/AddDict',
            formAddData
          );
        }

        if (response.data === true) {
          ElMessage.success(editingRow.value ? '更新成功' : '新增成功');
          closeDialog();
          if (searchTable.value) {
            searchTableData(selectedNodeId.value);
          } else {
            fetchTableData(selectedNodeId.value);
          }
        } else {
          ElMessage.error('操作失败：后端返回异常');
        }
      } catch (error) {
        if (error.response) {
          ElMessage.error(`操作失败: ${error.response.data || '未知错误'}`);
        } else {
          ElMessage.error('操作失败：请求未成功发送');
        }
      }
    };

    // 删除单行
    const deleteRow = (row) => {
      ElMessageBox.confirm('此操作将删除该列信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/api/Dict/DelDict?id=${row.dictionary_id}`)
          .then(response => {
            if (response.data === true) {
              ElMessage.success("删除成功");
              if (searchTable.value) {
                searchTableData(selectedNodeId.value);
              } else {
                fetchTableData(selectedNodeId.value);
              }
            } else {
              ElMessage.error("删除失败：后端返回失败");
            }
          })
          .catch(err => {
            console.error('删除失败:', err);
            ElMessage.error("删除失败：请求异常");
          });
      }).catch(() => {
        ElMessage.info("已取消删除");
      });
    };

    // 批量删除
    const batchDelete = async () => {
      if (multipleSelection.value.length === 0) {
        ElMessage.warning("请先选择要删除的项");
        return;
      }
      try {
        await ElMessageBox.confirm('此操作将删除选中的项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        const selectedIds = multipleSelection.value.map(item => item.dictionary_id);
        const response = await axios.put('/api/Dict/DelDicts', selectedIds, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        if (response.data === true) {
          ElMessage.success("批量删除成功");
          if (searchTable.value) {
            searchTableData(selectedNodeId.value);
          } else {
            fetchTableData(selectedNodeId.value);
          }
        } else {
          ElMessage.error("批量删除失败：后端返回失败");
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error("批量删除失败");
        } else {
          ElMessage.info("已取消批量删除");
        }
      }
    };

    // 重置
    const reset = () => {
      searchTable.value = '';
      searchKey.value = '';
      selectedFilter.value = '1';
      currentPage.value = 1;
      treeTableData(0);
    };

    // 分页
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      if (searchTable.value) {
        searchTableData(selectedNodeId.value); // 带搜索条件的分页
      } else {
        fetchTableData(selectedNodeId.value); // 普通分页
      }
    };

    // 选择变更
    const handleSelectionChange = (val) => {
      multipleSelection.value = val;
      isAllSelected.value = val.length === tableData.value.length;
    };

    // 节点点击
    const handleNodeClick = (data) => {
      selectedNodeId.value = data.dict_type_id;
      fetchTableData(selectedNodeId.value);
    };

    onMounted(() => {
      treeTableData(0);
    });

    return {
      emptyText,
      searchKey,
      treeData,
      defaultProps,
      tableData,
      selectedFilter,
      searchTable,
      currentPage,
      pageSize,
      totalItems,
      dialogVisible,
      dialogTitle,
      newDictForm,
      dictTypes,
      rules,
      editingRow,
      newDictFormRef,
      openDialog,
      closeDialog,
      confirmAdd,
      fetchDictTypes,
      updateState,
      batchDelete,
      deleteRow,
      handleNodeClick,
      handleFilterChange,
      handleCurrentChange,
      multipleSelection,
      isAllSelected,
      handleSelectionChange,
      reset,
      search,
      query
    };
  },
};
</script>

<style>
.container {
  display: flex;
  gap: 20px;
  height: 100%;
  width: 97%;
}

.sidebar {
  height: 90%;
}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 90%;
}

.tree-container {
  width: 100%;
  height: 100%;
}

.letree {
  height: 100%;
  font-size: 18px;
}

.center-text {
  text-align: center;
}

.el-select {
  width: 200px;
}

.letree .el-tree-node__content {
  text-align: center;
}

.letree .el-tree-node {
  margin-bottom: 10px;
}
</style>